import { CustomError } from '../../services/auth-inteceptor';
import { EmailValidator } from '../../shared/dynamicform/my-validator';
import { Company, Project } from '../../shared/model/defination';
import { Component, OnInit } from '@angular/core';
import { CompanyService } from 'services/company-service';
import { ManageService } from 'services/manage-service';
import { ProjectService } from 'services/project-service';
import { Manage } from 'shared/model/defination';
import { ControlBase } from 'shared/dynamicform/controlbase';
import { ActivatedRoute, Router } from '@angular/router';
import { MdlSnackbarService, MdlDialogService } from '@angular-mdl/core';
import { SessionService } from 'services/session-service';
import { Validators, FormGroup } from '@angular/forms';
import { TextBox } from 'shared/dynamicform/textbox-control';
import { MobileValidator } from 'shared/dynamicform/my-validator';
import { SelectBox } from 'shared/dynamicform/selectbox-control';
import { Helper } from 'app/common';

@Component({
    selector: 'app-register',
    templateUrl: './register.component.html',
    styleUrls: ['./register.component.scss'],
    providers: [CompanyService, ManageService, ProjectService]
})
export class RegisterComponent implements OnInit {
    public isPosting: boolean = false;
    public get IsEdit() {
        return this._route.snapshot.params['id'] !== undefined;
    }
    public get CanEditProject() {
        // return this.userRole === '管理员';
        return true;
    }
    public get CanEditCompany() {
        // return this.userRole.toLowerCase() !== 'hr';
        return true;
    }

    private _editItem: Manage;
    public isFormPosting: boolean = false;

    public locationProperties: Array<Location> = [];
    // ----------------------selected project----------------------------

    // public selectedBuilding: number;
    public selectedGender: number;
    public uploadPercent: number = 0;
    formInputs: ControlBase<any>[];
    formControls: any;
    public selectedRole: number;
    public roleMap: Array<{ key: string; value: number; alias: string }> = [
        // { key: '管理员', value: 1, alias: '管理员' },
        { key: '项目管理员', value: 2, alias: '项目管理员' },
        { key: '公司行政／HR', value: 3, alias: '公司行政／HR' },
        { key: '前台', value: 4, alias: '前台' }
    ];
    public avatarPhoto: any[] = [];
    public faceIds: number[] = [];
    public identifyPhoto: any[] = [];
    public userRole: string = '';
    public projects: Array<Project> = [];
    public selectedProject: Project;
    public company: Company;
    // @ViewChild('userForm') userForm: DynamicFormComponent;

    // public uploadedPhotoIds: number[] = [];

    constructor(
        private _route: ActivatedRoute,
        private _router: Router,
        private _companyService: CompanyService,
        private _mdlSnackbarService: MdlSnackbarService,
        private _sessionService: SessionService,
        private _manageService: ManageService,
        private _projectService: ProjectService,
        private _dialogService: MdlDialogService
    ) { }

    async ngOnInit() {
        try {
            this.isPosting = true;
            this.projects = await this._projectService.All().toPromise();
            // let session: Manage = await this._sessionService.getCurrentUser();
            // this.userRole = session.roles[0].roleName;
            // this.isPosting = true;
            // let userId = this.IsEdit ? +this._route.snapshot.params['id'] : 0;
            // if (userId) {
            //   this._editItem = await this._manageService.Get(userId).toPromise();
            //   let editUserRoleName = this._editItem.roles[0].roleName;
            //   this.selectedGender = this._editItem.gender;
            //   // this.selectedRole = this.roleMap.find(rm => rm.alias === editUserRoleName).value;
            //   this.selectedRole = this._editItem.roles.map(r => r.id)[0];
            //   if (this.selectedRole == 2) {

            //   }
            //   else if (this.selectedRole == 3) { // company
            //     let editItem = this._editItem as any;
            //     this.locationProperties = editItem.managements[0].managable.locations;
            //   }
            // }
            // else if (session.roles[0].roleName !== '管理员') {
            //   // 获取sessionUser的相关项信息，所属项目，如果是物业
            //   let sessionUser = await this._manageService.Get(session.id).toPromise();
            //   let companyId = sessionUser.company.id;
            //   let company = await this._companyService.Get(companyId).toPromise();
            // }

            this.formControls = this._setForm(this._editItem);
        } catch (e) {
            console.log(e);
            if (e.status === 401) {
                this._router.navigate(['/login']);
            }
        } finally {
            this.isPosting = false;
        }
    }
    public uploaded(event) {
        console.log(event);
        console.log(this.avatarPhoto);
    }

    public PercentCallBack(event) {
        console.log(this.uploadPercent);
        // console.log(event);
    }
    public uploaded2(event) {
        console.log(event);
        console.log(this.identifyPhoto);
        this.faceIds = this.identifyPhoto.map(ip => ip.faceId);
        console.log(this.faceIds);
    }
    private _setForm(data: any): any {
        this.formInputs = [
            new SelectBox({
                key: 'roleId',
                label: '角色',
                options: this._getCanEditRoles(),
                value: this.selectedRole,
                order: 4,
                groupId: 1,
                require: true,
                // disabled: !this.CanEditCompany,
                validators: Validators.required
            }),
            new TextBox({
                type: 'text',
                key: 'mobile',
                label: '手机号',
                value: data ? data.mobile : '',
                required: true,
                disabled: this.IsEdit,
                order: 10,
                groupId: 2,
                require: true,
                validators: [Validators.required, MobileValidator()]
            }),
            new TextBox({
                type: 'text',
                key: 'email',
                label: 'Email',
                value: data ? data.email : '',
                required: true,
                order: 1,
                groupId: 3,
                require: true,
                validators: [Validators.required, EmailValidator()]
            }),
            new TextBox({
                type: 'text',
                key: 'userName',
                label: '姓名',
                value: data ? data.userName : '',
                required: true,
                order: 2,
                groupId: 4,
                require: true,
                validators: Validators.required
            })
            // ,
            // new SelectBox({
            //     key: 'gender',
            //     label: '性别',
            //     options: [{ key: '女', value: '0' }, { key: '男', value: '1' }],
            //     value: this.selectedGender,
            //     order: 4,
            //     groupId: 3,
            //     require: true,
            //     // disabled: !this.CanEditCompany,
            //     validators: Validators.required
            // })
        ];
        return Helper.setGroupForm(this.formInputs);
    }
    async save(df: any) {
        this.isFormPosting = true;
        const form = <FormGroup>df.form;
        if (!form.valid) {
            return false;
        }
        const request: any = {
            userName: form.value.userName,
            gender: form.value.gender,
            mobile: form.value.mobile,
            password: '88888888',
            email: form.value.email || 'user@capitaland.com',
            // companyId: form.value.companyId,
            roleIds: [form.value.roleId]
        };
        if (this.selectedRole == 2) {
            request.manageId = this.selectedProject;
            request.manageType = 'project';
        } else if (this.selectedRole == 3) {
            request.manageId = this.company[0].id;
            request.manageType = 'company';
        } else if (this.selectedRole == 4) {
            request.manageId = this.selectedProject;
            request.manageType = 'receipt';
        }
        if (!request.manageId) {
            alert('请选择项目或者公司');
            return false;
        }
        let action;
        if (!this.IsEdit) {
            action = this._manageService.Create(request).toPromise();
        } else {
            request.id = this._editItem.id;
            // request.faceId = this._editItem.faceId;
            action = this._manageService.Update(request).toPromise();
        }
        try {
            let resp = await action;
            if (resp) {
                this._mdlSnackbarService.showToast('保存成功！', 2000);
                const roleName = this.roleMap.find(
                    r => r.value === this.selectedRole
                ).key;

                let ret = this._dialogService.alert(
                    `已经发送${roleName}创建申请给到凯德星，待系统核实确认后，会发送确认短信到手机，请注意查收。`,
                    '我知道了',
                    '已发送申请'
                );
                ret.subscribe(() => this._router.navigate(['/manage']));
            }
        } catch (e) {
            // this._mdlSnackbarService.showToast(e.msg, 2000);
            if (e instanceof CustomError) {
                const msg = Object.keys(e.msg)
                    .map(k => e.msg[k][0])
                    .join(',');

                this._mdlSnackbarService.showToast(msg, 2000);
            } else {
                this._mdlSnackbarService.showToast(e.msg, 2000);
            }
        } finally {
            this.isFormPosting = false;
        }
    }


    public projectChange(event) {

    }

    private _getCanEditRoles() {
        // let sessionRole = this.userRole.toLowerCase();
        // let sessionRoleMap = this.roleMap.find(r => r.key.toLowerCase() === sessionRole);

        // return this.roleMap.filter(r => r.value > sessionRoleMap.value);
        return this.roleMap;
    }

    public async onLoadFormData(form) {
        this.selectedRole = form.roleId;
    }
}
